package com.itheima.sh.esdemo;

import org.apache.http.HttpHost;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;


import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;

import org.elasticsearch.search.aggregations.AggregationBuilders;

import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class BulkSearch {

    //桶分组查询
    @Test
    public void bulk() throws Exception {
        // 1.创建SearchRequest对象，并制定索引库名称
        SearchRequest searchRequest = new SearchRequest("car");

        //2.创建SearchSourceBuilder对象，设置分组相关参数
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(
                AggregationBuilders
                        .terms("popular_color")
                        .field("color.keyword"));
        // 分页参数
        sourceBuilder.size(0);

        // 3.添加SearchSourceBuilder对象到SearchRequest对象source中
        searchRequest.source(sourceBuilder);
        // 4.执行查询
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        // 5.得到查询结果
        SearchHits responseHits = response.getHits();
        TotalHits totalHits = responseHits.getTotalHits();
        System.out.println("total："+totalHits.value);
        //解析数据
        Terms terms = (Terms) response.getAggregations().asMap().get("popular_color");
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            Object key = bucket.getKey();
            long docCount = bucket.getDocCount();
            System.out.println(key+"="+docCount);
        }
    }

//分组聚合
    @Test
    public  void arrtest() throws Exception {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置分组参数
        TermsAggregationBuilder popularColorAggs = AggregationBuilders.terms("popular_color").field("color.keyword");
        //分组后平均价格计算
        AvgAggregationBuilder priceAggs = AggregationBuilders.avg("avg_price").field("price");
        //按颜色分组后添加子聚合计算
        popularColorAggs.subAggregation(priceAggs);
        //添加条件
        sourceBuilder.aggregation(popularColorAggs);
        sourceBuilder.size(0);
        //创建查询对象
        SearchRequest request = new SearchRequest("car");
        request.source(sourceBuilder);
        //执行查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        long value = response.getHits().getTotalHits().value;
        System.out.println("总结果数为=" + value);
        //解析分组查询数据
        Terms terms = (Terms) response.getAggregations().asMap().get("popular_color");
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            Object key = bucket.getKey();
            long docCount = bucket.getDocCount();
            System.out.println(key+"="+docCount);
            //解析平均价格
            ParsedAvg avgPrice = (ParsedAvg)bucket.getAggregations().getAsMap().get("avg_price");
            System.out.println(key+"平均价格"+avgPrice.getValue());
        }

    }




    private RestHighLevelClient client;

    @Before
    public void init() throws IOException {
        //创建es客户端
        client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.200.150", 9200, "http")));
    }

    @After
    public void testrestclose() {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
